package com.systop.common.modules.init;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.acegisecurity.providers.encoding.PasswordEncoder;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.systop.common.modules.security.user.UserConstants;
import com.systop.common.modules.security.user.model.Role;
import com.systop.common.modules.security.user.model.User;
import com.systop.core.Constants;

/**
 * 用户及角色信息的数据初始化
 */
@SuppressWarnings("unchecked")
public class UserInitializer {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired(required = true)
	private SessionFactory sessionFactory;

	/** 用于加密 */
	@Autowired
	private PasswordEncoder passwordEncoder;

	private List<Role> sysRoles = null;

	/**
	 * spring自动调用方法,用于数据初始化
	 */
	@PostConstruct
	@Transactional
	public void init() {
		initRoles();
		initAdmin();
	}
	
	/**
	 * 初始化系统角色
	 */
	private void initRoles() {
		Session session = sessionFactory.openSession();
		try {
			if (!hasSysRole(session)) {
				for (Role role : defSysRoles()) {
					session.save(role);
				}
			}
		} finally {
			session.flush();
			session.close();
		}
	}

	/**
	 * 初始化管理员用户
	 */
	private void initAdmin() {
		Session session = sessionFactory.openSession();
		try {
			if (getAdmin(session) == null) {
				User admin = new User();
				admin.setLoginId(UserConstants.ADMIN);
				admin.setPassword(passwordEncoder
						.encodePassword(UserConstants.ADMIN_PASS, null));
				admin.setName(UserConstants.ADMIN_NAME);
				admin.setDescn("系统管理员");
				admin.setStatus(Constants.STATUS_AVAILABLE);
				admin.setIsSys(Constants.STATUS_AVAILABLE);
				// 设置角色
				admin.getRoles().add(getRole(session, UserConstants.ROLE_ADMIN));
				session.save(admin);
			}
		} finally {
			session.flush();
			session.close();
		}
	}

	private List<Role> defSysRoles() {
		if (sysRoles == null) {
			sysRoles = new ArrayList<Role>();
			sysRoles.add(new Role(UserConstants.ROLE_ADMIN, "系统管理员", Constants.YES));
			sysRoles.add(new Role(UserConstants.ROLE_GENERAL, "一般职员", Constants.YES));
		}
		return sysRoles;
	}

	/**
	 * 获得ADMIN帐户
	 */
	private User getAdmin(Session session) {
		List<User> users = session.createQuery(
				"from User u where u.loginId='admin'").list();
		return (users != null && !users.isEmpty()) ? users.get(0) : null;
	}

	/**
	 * 是否已经有系统角色
	 */
	private boolean hasSysRole(Session session) {
		List<Role> list = session.createQuery("from Role r where r.isSys=?")
				.setString(0, Constants.STATUS_AVAILABLE).list();
		return (list != null && list.size() > 0);
	}

	private Role getRole(Session session, String roleName) {
		List<Role> list = session
				.createQuery("from Role r where r.name = ? and r.isSys = '1'")
				.setParameter(0, roleName).list();
		return (list != null && !list.isEmpty()) ? list.get(0) : null;
	}
}
